﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using Utilities;

namespace StockCommon
{
    public class StockManager
    {

        protected static Dictionary<string,Hashtable> stockCodes = null;


        static String undefined = "未定義";
        public static String getStockName(String code)
        {
            initStockCodes();
            Hashtable ht = stockCodes[code];
            if (ht!=null)
                return (String)ht["名稱"];
            return undefined;
        }

        public static StockDataClassesDataContext getContext()
        {
            return LinqAgent.getContext();
        }

        public static List<String> getStockCodeLike(String like)
        {
            StockCommon.StockDataClassesDataContext context = StockCommon.LinqAgent.getContext();
            
            String opt = "";
            if (String.IsNullOrEmpty(like) == false)
            {
                opt = String.Format(" 代號 like '%{0}%' or 名稱 like '%{0}%') and ", like);
            }
            String sql = "select 代號+' '+名稱  as codeName from StockIndex where " + opt + " LEN([代號])<=4 order by 市場,代號";
            List<String> result = context.ExecuteQuery<String>(sql).ToList<String>();
            return result;
        }
        protected static bool updateStockCategory_internal(String code, String catName, Guid catId, String 市場)
        {
            StockDataClassesDataContext context = getContext();
            StockIndex si = (from c in context.StockIndexes where c.代號 == code select c).FirstOrDefault<StockIndex>();
            if (si == null)
                return false;
            if (catId.Equals(si.catId))
                return true;
            si.catId = catId;
            si.市場 = 市場;
            si.類別 = catName;
            si.國家 = "tw";
            context.SubmitChanges();
            return true;
        }
        public static bool updateOtcStockCategory(String code, String catName, Guid catId)
        {
            return updateStockCategory_internal(code, catName, catId, "otc");
        }

        public static bool updateTseStockCategory(String code, String catName,Guid catId)
        {
            return updateStockCategory_internal(code, catName, catId, "tse");
        }



        protected static Guid updateBasicCategory(string catName, string catCode, int seq, String market)
        {
            StockCategory cc = (from c in getContext().StockCategories where (c.market == market && c.catId == catCode) select c).FirstOrDefault<StockCategory>();
            if (cc != null)
                return cc.id;
            cc = new StockCategory();
            cc.id = NewGUID.create("cate");
            cc.catgoryName = catName;
            cc.isBasic = true;
            cc.seq = seq;
            cc.market = market;
            cc.catId = catCode;
            StockDataClassesDataContext context = getContext();
            context.StockCategories.InsertOnSubmit(cc);
            context.SubmitChanges();
            return cc.id;
        }
        public static Guid UpdateOtcBasicCategory(string catName, string catCode, int seq)
        {
            return updateBasicCategory(catName, catCode, seq, "otc");
        }


        public static  Guid  UpdateTseBasicCategory(String catName, String catCode,int seq)
        {
            return updateBasicCategory(catName, catCode, seq, "tse");
         
        }      


        public StockManager()
        {
            initStockCodes();

        }
        private static void initStockCodes()
        {
            if (stockCodes != null)
                return;
            stockCodes = new  Dictionary<string,Hashtable>();
            StockDataClassesDataContext context = LinqAgent.getContext();
            
            List<StockIndex> ll = (from i in context.StockIndexes select i).ToList<StockIndex>();
            foreach (StockIndex si in ll)
            {
                Hashtable ht = new Hashtable();
                ht["市場"] = si.市場;
                ht["代號"]=si.代號;
                ht["名稱"] = si.名稱;
                ht["id"] = si.id;
                stockCodes[si.代號] = ht;
            }
        }
        
        protected void fixToOtc(String code)
        {
            String sql = String.Format("update StockIndex set [市場]='otc' where  [代號]= '{0}'", code);
            StockDataClassesDataContext context = LinqAgent.getContext();
            context.ExecuteCommand(sql);
            context.SubmitChanges();

        }
        public Guid getGreTaiId(String code)
        {
            if (stockCodes.ContainsKey(code))
            {
                Hashtable ht = stockCodes[code];
                if ("otc".Equals(ht["市場"]) == false)
                {
                    fixToOtc(code);
                    ht["市場"] = "otc";
                }
                return (Guid)ht["id"];
            }
            //因為一開始已經insert
            return Guid.Empty;
        }
        public Guid createGreTai(String code, String name,DateTime d, int 發行量=0)
        {
            if (stockCodes.ContainsKey(code))
            {
                Hashtable ht1 = stockCodes[code];
                return (Guid)ht1["id"];
            }

            StockIndex si = new StockIndex();
            si.代號 = code;
            si.名稱 = name;
            si.市場 = "otc";
            if (發行量 != 0)
                si.發行量 = 發行量;
            si.是否有效 = true;
            si.最後資料日期 = DateUtils.getDateOnly(d);
            si.id = NewGUID.create("stck");
            StockDataClassesDataContext context = LinqAgent.getContext();
            context.StockIndexes.InsertOnSubmit(si);
            
            Hashtable ht = new Hashtable();
            ht["市場"] = si.市場;
            ht["代號"] = si.代號;
            ht["名稱"] = si.名稱;
            ht["id"] = si.id;
            stockCodes[si.代號] = ht;

            return si.id;
        }





        public static List<string> getRecentValidStockCodes()
        {
            DateTime dt = DateTime.Now;
            dt=dt.AddDays(-100);
            String sql = string.Format("select distinct 證券代號 from StockDaily where 日期 >'{0}' and LEN(證券代號) < 5 order by 證券代號", DateUtils.toYYYYMMDD_Slash(dt));
            StockDataClassesDataContext context = getContext();
            List<string> result=context.ExecuteQuery<String>(sql).ToList<String>();
            return result;
        }
    }
}
